﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DatabaseComponent;
using System.IO;

public partial class HintsViewEN : System.Web.UI.Page
{

    


    public List<Hints> lstHintsGrid
    {
        get
        {
            if (ViewState["lstHintsGrid"] == null)
            {
                ViewState["lstHintsGrid"] = System.Guid.NewGuid().ToString();
            }


            if (Session[ViewState["lstHintsGrid"].ToString()] == null)
            {
                Session[ViewState["lstHintsGrid"].ToString()] = new List<Hints>();

            }

            return (List<Hints>)Session[ViewState["lstHintsGrid"].ToString()];

        }
        set
        {
            if (ViewState["lstHintsGrid"] == null)
            {
                ViewState["lstHintsGrid"] = System.Guid.NewGuid().ToString();
            }

            Session[ViewState["lstHintsGrid"].ToString()] = value;
        }   
   
   

    }




    long mHintsID
    {
        get
        {
            if (ViewState["mHintsID"] == null)
            {
                ViewState["mHintsID"] = System.Guid.NewGuid().ToString();
            }


            if (Session[ViewState["mHintsID"].ToString()] == null)
            {
                long obj = -1;
                Session[ViewState["mHintsID"].ToString()] = obj;

            }

            return (long)Session[ViewState["mHintsID"].ToString()];

        }
        set
        {
            if (ViewState["mHintsID"] == null)
            {
                ViewState["mHintsID"] = System.Guid.NewGuid().ToString();
            }

            Session[ViewState["mHintsID"].ToString()] = value;
        }
    }


    Hints mObjHints
    {
        get
        {
            if (ViewState["mObjHints"] == null)
            {
                ViewState["mObjHints"] = System.Guid.NewGuid().ToString();
            }


            if (Session[ViewState["mObjHints"].ToString()] == null)
            {
                Session[ViewState["mObjHints"].ToString()] = new Hints();

            }

            return (Hints)Session[ViewState["mObjHints"].ToString()];

        }
        set
        {
            if (ViewState["mObjHints"] == null)
            {
                ViewState["mObjHints"] = System.Guid.NewGuid().ToString();
            }

            Session[ViewState["mObjHints"].ToString()] = value;
        }
    }






    protected void Page_Load(object sender, EventArgs e)
    {



        Persons objPersons = GlobalVars.getCurrentPerson();
        checkSecurityAndCustomizePage(objPersons);
       
        if (!Page.IsPostBack)
        {
            
            bindGrid("");
            editLoad();
        }

        

    }



    /// <summary>
    /// this function will bind the grid 
    /// </summary>
    protected void bindGrid(string strIn)
    {

        List<Hints> lstHints = search(strIn);



        lstHintsGrid = lstHints;

        grdUsers.DataSource = lstHints;
        grdUsers.DataBind();
    }



    /// <summary>
    /// it will check the security and customize the page
    /// </summary>
    /// <param name="currentPerson">the person to set security to his previleges</param>
    protected void checkSecurityAndCustomizePage(Persons currentPerson)
    {
        //Security Check

        if (!currentPerson.lstAllRulesIDs.Contains((long)RulesEnum.Hints_page))
            Response.Redirect("LoginEN.aspx");


        if (!currentPerson.lstAllRulesIDs.Contains((long)RulesEnum.Editing_hints_page))
        {
            btnSave.Enabled = false;
            btnDelete.Enabled = false;
        }
       




    }
    
    protected void btnSearch_Click(object sender, EventArgs e)
    {

        bindGrid(txtSearch.Text);
       
    }

    /// <summary>
    /// this function will search in hints and return the values
    /// </summary>
    /// <param name="txtText">the text to search for</param>
    /// <returns>a list of hints matched</returns>
    protected List<Hints> search(string txtText)
    {
        HintsDB objHintsDB = new HintsDB(ConnectionStrings.LMS);
        List<Hints> lstRet = new List<Hints>();
        if (txtText.Trim() == "")
        {
            List<Hints> lstNew = objHintsDB.Select(" top 100 ", " order by [HintTitleEN] ");
            //lstNew = new List<TicketType>(from objFol in lstNew where objFol.StatusID != 2 select objFol);
            //no status
            return lstNew;
        }

        string[] strValues = null;
        if (txtText.Trim()[0] == '\"' && txtText.Trim()[txtText.Trim().Length - 1] == '\"')
        {
            try
            {
                strValues = new string[] { txtText.Trim().Substring(1, txtText.Trim().Length - 2) };
                if (strValues[0] == "")
                    strValues = new string[0];
            }
            catch
            {
                strValues = new string[0];
            }
        }
        else
        {
            strValues = txtText.Trim().Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
        }

        foreach (string strValue in strValues)
        {
            Hints objHints = new Hints();
            objHints.HintTitleAR = objHints.HintTitleEN = objHints.HintDetailsAR = objHints.HintDetailsEN = "%" + strValue + "%";
            List<Hints> lstHints = objHintsDB.SearchOrLike(objHints);
            //lstTicketType = new List<TicketType>(from objFol in lstTicketType where objFol.StatusID != 2 select objFol);
            //no status
            foreach (Hints objFol in lstHints)
            {
                if ((from objIn in lstRet where objIn.ID == objFol.ID select objIn).ToList().Count == 0)
                {
                    lstRet.Add(objFol);
                }
            }

        }


        return lstRet;



    }





    protected void grdUsers_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {

        Persons objCurrentPersons = GlobalVars.getCurrentPerson();
        checkSecurityAndCustomizePage(objCurrentPersons);

        //security check

        if (!objCurrentPersons.lstAllRulesIDs.Contains((long)RulesEnum.Editing_hints_page))
        {
            lblError.Text = "Security error , you can view only";
            lblResult.Text = "";

            return;
        }


        long HintsID = long.Parse(grdUsers.DataKeys[e.RowIndex]["ID"].ToString());



        HintsDB objHintsDB = new HintsDB(ConnectionStrings.LMS);
        List<Hints> lstHints = objHintsDB.getHintsByID(HintsID);




        if (lstHints.Count == 0)
        {
            lblError.Text = "No Hints to delete";
            lblResult.Text = "";
            return;
        }






        objHintsDB.Delete(lstHints[0]);
        try
        {
            File.Delete(Server.MapPath("~/LmsWebSite/HintsImages/" + mObjHints.HintImage));
        }
        catch
        {
        }


        lblResult.Text = "Deleted ok.";



        bindGrid(txtSearch.Text);



    }




    protected void btnNew_Click(object sender, EventArgs e)
    {
        clearAllControls();
    }



    protected void grdUsers_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grdUsers.DataSource = lstHintsGrid;
        grdUsers.PageIndex = e.NewPageIndex;

        grdUsers.DataBind(); 
    }


    /// <summary>
    /// this function will check mHintsID to detect update or insert
    /// </summary>
    protected void checkID()
    {
        if (mHintsID != -1)
        {
            try
            {

                HintsDB objHintsDB = new HintsDB(ConnectionStrings.LMS);
                List<Hints> lstHints = objHintsDB.getHintsByID(mHintsID);
                if (lstHints.Count > 0)
                {


                    mObjHints = lstHints[0];
                    btnDelete.Visible = true;

                }
                else
                {
                    mHintsID = ((long)-1);
                   
                    
                }


            }
            catch
            {
                mHintsID = ((long)-1);
                
            }


            
        }
        else
        {
            btnDelete.Visible = false;

        }
    }



    /// <summary>
    /// this will bind the Hints to update or delete
    /// </summary>
    protected void BindAllControls()
    {
        calenderHintDate.set(DateTime.Now);
        if (mHintsID != -1)
        {

            txtHintTitleAR.Text = mObjHints.HintTitleAR;
            txtHintTitleEN.Text = mObjHints.HintTitleEN;
            txtHintDetailsAR.Text = mObjHints.HintDetailsAR;
            txtHintDetailsEN.Text = mObjHints.HintDetailsEN;

            calenderHintDate.set(mObjHints.HintDate);
            
            if (mObjHints.HintImage.Trim() != "")
            {
                imgHint.Src = "~/LmsWebSite/getImage.ashx?Image=HintsImages/" + mObjHints.HintImage + "&w=100&h=100&color=White";
                lnkImage.HRef = "~/LmsWebSite/HintsImages/" + mObjHints.HintImage;
                lblHintImageValue.Text = mObjHints.HintImage;

            }
            else
            {
                imgHint.Src = "";
                lblHintImageValue.Text = "";
                lnkImage.HRef = "#";
            }




        }
    }



    /// <summary>
    /// this function will read all controls values
    /// </summary>
    protected void ReadAllControls()
    {

        mObjHints.HintTitleEN = txtHintTitleEN.Text;
        mObjHints.HintTitleAR = txtHintTitleAR.Text;
        mObjHints.HintDetailsAR = txtHintDetailsAR.Text;
        mObjHints.HintDetailsEN = txtHintDetailsEN.Text;

        DateTime? hintCurrentDate = null;
        calenderHintDate.get(ref hintCurrentDate);

        if (hintCurrentDate == null)
            hintCurrentDate = DateTime.Now;


        mObjHints.HintDate = hintCurrentDate.Value;

        string strFilename = "";



        if (fuImage.HasFile)
        {
            strFilename = System.Guid.NewGuid().ToString() + ".jpg";


            try
            {
                fuImage.SaveAs(Server.MapPath("~/LmsWebSite/HintsImages/" + strFilename));
            }
            catch
            {
                lblError.Text = "Error saving Image file";
                strFilename = "";
            }

        }
        else
        {
            strFilename = lblHintImageValue.Text;
        }


        mObjHints.HintImage = strFilename;
               



    }



    /// <summary>
    /// this function for clearing controls
    /// </summary>
    protected void clearAllControls()
    {
        txtHintTitleAR.Text = "";
        txtHintTitleEN.Text ="";
        txtHintDetailsAR.Text = "";
        txtHintDetailsEN.Text = "";

        calenderHintDate.clear();

        
        imgHint.Src = "";
        lblHintImageValue.Text = "";
        lnkImage.HRef = "#";

        mObjHints = new Hints();

    }



    /// <summary>
    /// this function for loading the editing behavior
    /// </summary>
    protected void editLoad()
    {


        Persons currentPerson = GlobalVars.getCurrentPerson();




       

            checkSecurityAndCustomizePage(currentPerson);

            checkID();


            BindAllControls();




        
    }



    /// <summary>
    /// this function will Save the hint
    /// </summary>
    protected void Save()
    {


        if (checkForRepeats())
        {
            HintsDB objHintsDB = new HintsDB(ConnectionStrings.LMS);
            if (mObjHints.ID == -1)
            {
                objHintsDB.Insert(mObjHints);
                clearAllControls();
                bindGrid(txtSearch.Text);
                lblResult.Text = "Data saved ok.";
            }
            else
            {
                objHintsDB.Update(mObjHints);
                BindAllControls();
                bindGrid(txtSearch.Text);
                lblResult.Text = "Data saved ok.";

            }



        }


    }


    /// <summary>
    /// this function will check if a hint  exists with the same Name or not
    /// </summary>
    /// <returns>true if ok , false for error (hint exists before)</returns>
    protected bool checkForRepeats()
    {
        HintsDB objHintsDB = new HintsDB(ConnectionStrings.LMS);



        List<Hints> lstOldHints = objHintsDB.getHintsByHintTitleAR (mObjHints.HintTitleAR);

        List<Hints> lstExist = new List<Hints>(from objOrg in lstOldHints where (objOrg.HintTitleAR == mObjHints.HintTitleAR && objOrg.ID != mObjHints.ID) select objOrg);

        if (lstExist.Count > 0)
        {

            errorExist();
            return false;
        }


        lstOldHints = objHintsDB.getHintsByHintTitleEN (mObjHints.HintTitleEN);

        lstExist = new List<Hints>(from objOrg in lstOldHints where (objOrg.HintTitleEN == mObjHints.HintTitleEN && objOrg.ID != mObjHints.ID) select objOrg);

        if (lstExist.Count > 0)
        {

            errorExist();
            return false;
        }





        return true;

    }




    /// <summary>
    /// this function will show a message with the error for existense
    /// </summary>
    private void errorExist()
    {

        lblError.Text = "Error , a hint the same title  is already found , choose a new title";

    }



    protected void btnSave_Click(object sender, EventArgs e)
    {

        //security check
        Persons currentPerson = GlobalVars.getCurrentPerson();
        if (!currentPerson.lstAllRulesIDs.Contains((long)RulesEnum.Editing_hints_page))
            return;


        if (Page.IsValid)
        {



            ReadAllControls();






            Save();


        }
    }




    protected void btnDelete_Click(object sender, EventArgs e)
    {

        //security check
        Persons currentPerson = GlobalVars.getCurrentPerson();
        if (!currentPerson.lstAllRulesIDs.Contains((long)RulesEnum.Editing_hints_page))
            return;


        ReadAllControls();


        long HintsID = mHintsID;




        HintsDB objHintsDB = new HintsDB(ConnectionStrings.LMS);
        List<Hints> lstHints = objHintsDB.getHintsByID(HintsID);




        if (lstHints.Count == 0)
        {
            lblError.Text = "No hints to delete";
            lblResult.Text = "";
            return;
        }





       


        objHintsDB.Delete(lstHints[0]);
        try
        {
            File.Delete(Server.MapPath("~/LmsWebSite/HintsImages/" + mObjHints.HintImage));
        }
        catch
        {
        }

        bindGrid(txtSearch.Text);
        lblResult.Text = "Deleted ok.";



        

        clearAllControls();






    }




    protected void grdUsers_RowEditing(object sender, GridViewEditEventArgs e)
    {
        Persons objCurrentPersons = GlobalVars.getCurrentPerson();
        checkSecurityAndCustomizePage(objCurrentPersons);



        long HintsID = long.Parse(grdUsers.DataKeys[e.NewEditIndex]["ID"].ToString());

        mHintsID = HintsID;

        editLoad();

        e.Cancel = true;

        

    }



    protected void cvHintDate_ServerValidate(object sender, ServerValidateEventArgs e)
    {
        DateTime? dtNew = null;
        if (calenderHintDate.get(ref dtNew))
        {
            e.IsValid = true;
        }
        else
        {
            e.IsValid = false;
        }
    }


}
